// components/lyric/lyric.js
let lyricHeigth = 0
Component({
  /**
   * 组件的属性列表
   */
  properties: {
    isLyricShow: {
      type: Boolean,
      value: false
    },
    lyric: String
  },
  observers: {
    lyric (lyr) {
      if (lyr == '暂无歌词') {
        this.setData({
          lrcList: [{
            lyr,
            time: 0,
          }],
          nowLyricIndex: -1
        })
      } else {
        this.parseLyric(lyr)
      }
    }
  },

  /**
   * 组件的初始数据
   */
  data: {
    lrcList: [],
    nowLyricIndex: 0,
    scrollTop: 0
  },
  lifetimes: {
    ready () {
      wx.getSystemInfo({
        success (res) {
          lyricHeigth = res.screenHeight / 1334 * 64
        }
      })
    }
  },
  /**
   * 组件的方法列表
   */
  methods: {
    update (currentTime) {
      let lrcList = this.data.lrcList
      let len = lrcList.length
      if(len === 0){
          return;
        }
      if(currentTime > lrcList[len - 1].time){
        if(this.data.nowLyricIndex !== -1){
          this.setData({
            nowLyricIndex: -1,
            scrollTop: len * lyricHeigth
          })
          console.log(111)
        }
      }
      for(let i = 0; i < len; i++){
        if(currentTime <= lrcList[i].time){
          let height =  (i -1) * lyricHeigth
          if(this.data.scrollTop === height){
            break
          }
          if ((len * lyricHeigth) -this.data.scrollTop < 100){
            break
          }
          this.setData({
            nowLyricIndex: i - 1,
            scrollTop: (i -1) * lyricHeigth
          })
          console.log(this.data.scrollTop)
          break
        }
      }
    },
    parseLyric (lyric) {
      let line = lyric.split('\n')
      let lrcList = []
      line.forEach((item) => {
        //分割时间
        let time = item.match(/\[(\d{2,}):(\d{2})(?:\.(\d{2,3}))?]/g)
        if(time != null){
          //以时间分割歌词
          let lrc = item.split(time)[1]
          //分割时间字符串，取到分钟、秒、毫
          let timeReg = time[0].match(/(\d{2,}):(\d{2})(?:\.(\d{2,3}))?/)
          let timeSeconds = parseInt(timeReg[1]) * 60 + parseInt(timeReg[2]) + parseInt(timeReg[3] / 1000)
          lrcList.push({
            lrc,
            time: timeSeconds
          })
          this.setData({
            lrcList
          })
        }
      })
    }
  }
})
